package com.baizhi.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 前后端分离，异常处理
 */
@ControllerAdvice   // 给controller增加一些附加操作
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 自定义方法，希望可以处理所有controller异常
     */
    @ExceptionHandler   // 用来处理controller异常
    @ResponseBody
    private Map<String, Object> exception(Exception ex) {
        log.info("ex: {}", ex.getMessage());
        HashMap<String, Object> result = new HashMap<>();
        result.put("msg", ex.getMessage());
        result.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
        return result;
    }
}
